﻿using LocoyApp.Locoy.Entry;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace LocoyApp.Locoy
{
    public class ContentRewrite : LocoyCode
    {
        /// <summary>
        /// 执行方法，不能修改类和方法名称。
        /// </summary>
        /// <param name="content">标签内容</param>
        /// <param name="response">页面响应，包含了Url、原始Html等属性</param>
        /// <returns>返回处理后的标签内容</returns>
        public string Run(string content, ResponseEntry response)
        {
            content = Rewrite(content);
            //在这里编写处理代码
            return content;
        }

        private string Rewrite(string content)
        {
            var form = new Dictionary<string, string>
            {
                { "wenzhang", content },
            };

            var response = Request("http://api3.123falv.com/api.php?json=0&v=1&key=cix2023", form, Encoding.GetEncoding("GB2312"));

            return response;
        }

        private string Request(string url, Dictionary<string, string> form, Encoding encoding, int timeout = 60)
        {
            NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
            foreach(var t in form)
                queryString.Add(t.Key, t.Value);

            string responseContent = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(queryString.ToString()); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
                webReq.Method = "POST";
                webReq.Timeout = timeout * 1000;
                //这里的格式根据自己需求替换
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;
                webReq.Headers.Add("Accept-Encoding", "");
                using (Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
                }
                using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding, true))
                    {
                        responseContent = sr.ReadToEnd();
                        //var regex = new System.Text.RegularExpressions.Regex(@"(%[ua-f0-9 ]+)");
                        responseContent = new System.Text.RegularExpressions.Regex(@"\s+").Replace(responseContent, "");
                        responseContent = HttpUtility.UrlDecode(responseContent);
                    }
                }
            }
            catch
            {
                return "";
            }

            return responseContent;
        }

        //private string Request2(string url, Dictionary<string, string> form, Encoding encoding, int timeout = 60)
        //{
        //    using (var httpClient = new System.Net.Http.HttpClient())
        //    {
        //        try
        //        {
        //            httpClient.Timeout = TimeSpan.FromSeconds(timeout);
        //            //HttpContent是HTTP实体正文和内容标头的基类。
        //            var httpContent = new System.Net.Http.FormUrlEncodedContent(form);

        //            //发送异步Post请求
        //            var response = httpClient.PostAsync(url, httpContent).Result;
        //            response.EnsureSuccessStatusCode();
        //            string resultStr = response.Content.ReadAsStringAsync().Result;

        //            return resultStr;
        //        }
        //        catch
        //        {
        //            return "";
        //        }
        //    }
        //}
    }
}
